using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;

using PartyBoy.TweetMode.Components;
using Twitterizer;
using DotNetNuke.Common;

namespace PartyBoy.Modules.TweetMode
{
    public partial class ViewTweetMode : PortalModuleBase, IActionable
    {
        #region Constants
        private const string TOKEN = "Token";
        private const string OAUTH_TOKEN_QUERY = "oauth_token";
        private const string OAUTH_VERIFIER_QUERY = "oauth_verifier";
        #endregion

        #region Event Handlers
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    TweetModeSettings settings = new TweetModeSettings(this.TabModuleId);
                    string consumerKey = settings.ConsumerKey;
                    string consumerSecret = settings.ConsumerSecret;
                    if (string.IsNullOrEmpty(consumerKey) || string.IsNullOrEmpty(consumerSecret))
                    {
                        mvTweetMode.SetActiveView(vwNoSetup);
                    }
                    else
                    {
                        OAuthTokens token = GetTokenFromSession();
                        if (token == null)
                        {
                            string oAuthTokenQuery = GetOAuthTokenQuery();
                            string oAuthVerifierQuery = GetOAuthVerifierQuery();
                            if (string.IsNullOrEmpty(oAuthTokenQuery) && string.IsNullOrEmpty(oAuthVerifierQuery))
                            {
                                string callbackUrl = Globals.NavigateURL(this.TabId);
                                OAuthTokenResponse requestToken = OAuthUtility.GetRequestToken(consumerKey, consumerSecret, callbackUrl);
                                Uri authorizationUri = OAuthUtility.BuildAuthorizationUri(requestToken.Token);
                                hpAuthorize.NavigateUrl = authorizationUri.AbsoluteUri;
                                mvTweetMode.SetActiveView(vwAuthorize);
                            }
                            else
                            {
                                OAuthTokenResponse accessToken = OAuthUtility.GetAccessToken(consumerKey, consumerSecret, oAuthTokenQuery, oAuthVerifierQuery);
                                OAuthTokens authorizedToken = new OAuthTokens
                                {
                                    AccessToken = accessToken.Token,
                                    AccessTokenSecret = accessToken.TokenSecret,
                                    ConsumerKey = consumerKey,
                                    ConsumerSecret = consumerSecret
                                };
                                Session.Add(TOKEN + TabModuleId, authorizedToken);
                                Response.Redirect(Globals.NavigateURL(this.TabId));
                            }
                        }
                        else
                        {
                            LoadStatuses();
                            mvTweetMode.SetActiveView(vwTimeLine);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtStatus.Text))
            {
                lblMessage.Text = "You have to enter something first.<br/>";
                return;
            }
            if (txtStatus.Text.Length > 140)
            {
                lblMessage.Text = "Your tweet is too long.<br/>";
                return;
            }
            OAuthTokens token = GetTokenFromSession();
            if (TwitterStatus.Update(token, txtStatus.Text, new StatusUpdateOptions()) != null)
            {
                lblMessage.Text = "Your tweet has been posted successfully.";
                txtStatus.Text = string.Empty;
                LoadStatuses();
            }
        }
        protected void lnkDisconnect_Click(object sender, EventArgs e)
        {
            Session.Remove(TOKEN + TabModuleId);
            Response.Redirect(Globals.NavigateURL(TabId));
        }
        #endregion

        #region Methods
        protected string LinkifyText(string text)
        {
            string pathToUserPage = string.Format("{0}/user.aspx", Request.Path);
            text = System.Text.RegularExpressions.Regex.Replace(text, @"@([^ ]+)", string.Format(@"@<a href=""{0}?username=$1"" ref=""nofollow"" target=""_blank"">$1</a>", pathToUserPage));
            text = System.Text.RegularExpressions.Regex.Replace(text, @"(?<addr>http://[^ ]+|www\.[^ ]+)", @"<a href=""${addr}"" ref=""nofollow"" target=""_blank"">$1</a>");
            return text;
        }
        private void LoadStatuses()
        {
            OAuthTokens token = GetTokenFromSession();
            var response = TwitterTimeline.HomeTimeline(token, new TimelineOptions());
            dlStatuses.DataSource = response.ResponseObject;
            dlStatuses.DataBind();
        }
        private OAuthTokens GetTokenFromSession()
        {
            return Session[TOKEN + TabModuleId] == null ? null : Session[TOKEN + TabModuleId] as OAuthTokens;
        }
        private string GetOAuthTokenQuery()
        {
            return Request.QueryString[OAUTH_TOKEN_QUERY] == null ? string.Empty : Request.QueryString[OAUTH_TOKEN_QUERY];
        }
        private string GetOAuthVerifierQuery()
        {
            return Request.QueryString[OAUTH_VERIFIER_QUERY] == null ? string.Empty : Request.QueryString[OAUTH_VERIFIER_QUERY];
        }
        #endregion

        #region IActionable Members
        public DotNetNuke.Entities.Modules.Actions.ModuleActionCollection ModuleActions
        {
            get
            {
                //create a new action to add an item, this will be added to the controls
                //dropdown menu
                ModuleActionCollection actions = new ModuleActionCollection();
                actions.Add(GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile),
                    ModuleActionType.AddContent, "", "", EditUrl(), false, DotNetNuke.Security.SecurityAccessLevel.Edit,
                     true, false);

                return actions;
            }
        }
        #endregion
    }
}